/**
 * 
 */
package com.surelution.cppei.weixin.gate

import static com.surelution.whistle.core.Attribute.*

import java.util.Map.Entry

import javax.servlet.ServletRequest

import com.surelution.whistle.core.Attribute
import com.surelution.whistle.core.BaseAction
import com.surelution.whistle.push.Exchange

/**
 * @author <a href="mailto:guangzong.syu@gmail.com">guangzong</a>
 *
 */
abstract class CppeiBaseAction extends BaseAction {

	private static ThreadLocal<ServletRequest> map = new ThreadLocal<ServletRequest>()
	
	public static void initRequest(ServletRequest sr) {
		map.set(sr)
	}

	private boolean isDelegateToSubAccount = false
	
	public void delegateToSubAccount() {
		isDelegateToSubAccount = true
	}
	
	private HashMap tempMap = new HashMap()
	
	/**
	 * TODO 不知道为毛这儿非要这个getter 和 setter 才可以运行通过，
	 * 要不然，总是说没有这个member
	 * guangzong.syu@gmail.com
	 * @return
	 */
	public HashMap getTempMap() {
		if(!tempMap) {
			tempMap = new HashMap()
		}
		return tempMap
	}
	public HashMap setTempMap(HashMap m) {
		tempMap = m
	}
	
	private Subscriber subscriber;

	final public String getRootPath() {
		ServletRequest r = map.get()
		return r.getServerName() + r.getServletContext().getContextPath()
	}

	final public void preExecute() {
		String openId = getParam(KEY_FromUserName)
		subscriber = Subscriber.findByOpenId(openId)
		if(!subscriber) {
			subscriber = new Subscriber()
			subscriber.openId = openId
			subscriber.save(flush:true)
		}
		
		Set<String> paramNames = paramNames()
		IncomeMessage imsg = new IncomeMessage()
		imsg.content = getParam(KEY_Content)
		
		imsg.createTime = Long.parseLong(getParam(KEY_CreateTime))
		imsg.fromUserName = getParam(KEY_FromUserName) 
		imsg.msgId = getParam("MsgId")
		imsg.msgType = getParam(KEY_MsgType)
		imsg.toUserName = getParam(KEY_ToUserName)
		imsg.save(flush:true)

		paramNames.remove(KEY_Content)
		paramNames.remove(KEY_CreateTime)
		paramNames.remove(KEY_FromUserName)
		paramNames.remove("MsgId")
		paramNames.remove(KEY_MsgType)
		paramNames.remove(KEY_ToUserName)

		paramNames.each {name ->
			AdditionalIncomeMessage aimsg = new AdditionalIncomeMessage()
			aimsg.message = imsg
			aimsg.name = name
			aimsg.value = getParam(name)
			aimsg.save(flush:true)
		}
		
	}
	
	protected Subscriber getSubscriber() {
		subscriber
	}
    
    protected boolean isMenu(String key) {
        getParam(KEY_MsgType) == "event" && getParam("Event") == "CLICK" && getParam("EventKey") == key
    }
	
	private String repackageFor(SubAccount sa) {
		paramNames().each {name->
			tempMap.put(name, new Attribute(name, getParam(name)))
		}
		
		SubscriberSubAccount ssa = SubscriberSubAccount.findBySubAccountAndSubscriber(sa, subscriber)
		tempMap.put(Attribute.KEY_FromUserName, new Attribute(Attribute.KEY_FromUserName, ssa.userid))
		
		StringBuilder sb = new StringBuilder();
		sb.append("<xml>");
		for(Entry<String, Attribute> entry : tempMap.entrySet()) {
			sb.append(entry.getValue().toXml());
		}
		sb.append("</xml>");
		return sb.toString();
	}

	private String changeToUsername(String c, String to) {
		//<ToUserName><![CDATA[123]]></ToUserName>
		String b = "<ToUserName><![CDATA["
		String a = "]]></ToUserName>"
		String s1 = c.substring(0,c.indexOf(b) + b.length())
		String s2 = c.substring(c.indexOf(a))
		s1 + to + s2
	}
	
	/* (non-Javadoc)
	 * @see com.surelution.whistle.core.BaseAction#buildXml()
	 */
	@Override
	public String buildXml() {
		if(!isDelegateToSubAccount) {
			return super.buildXml();
		} else {
			def subAccount = subscriber.account.subAccount
			def url = subAccount.hostUrl
			Exchange e = new Exchange()
			e.apiUrl = subAccount.hostUrl
			String r = repackageFor(subAccount)
			String ret = e.push(r)
			return changeToUsername(ret, subscriber.openId)
		}
	}
}
